package com.example.demo.concurrent.Lock.AQS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-04-15
 * Time: 12:43
 */
//自定义锁
public class MyLock implements Lock {

    //独占锁 -->同步器类
    class MySync extends AbstractQueuedSynchronizer {
        @Override //尝试获取锁
        protected boolean tryAcquire(int arg) {
            if(compareAndSetState(0,1)) {
                //成功加锁,设置owner为当前持有锁线程
                setExclusiveOwnerThread(Thread.currentThread());
                //当前线程加锁成功
                return true;
            }
            return false;
        }

        @Override //尝试释放锁
        protected boolean tryRelease(int arg) {
            setExclusiveOwnerThread(null);
            setState(0);//被volatile修饰->加了写屏障,保证可见性
            return true;
        }

        @Override //当前线程是否持有锁
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }
        //返回条件变量
        public Condition newCondition() {
            return new ConditionObject();
        }

    }

    private MySync sync = new MySync();

    @Override //加锁,成功则加锁成功,否则进入阻塞队列中等待
    public void lock() {
        sync.acquire(1);
    }

    @Override //加锁(可以被打断)
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    @Override // 尝试加锁一次
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    @Override //尝试加锁(有时限的尝试)
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1,unit.toNanos(time));
    }

    @Override //解锁
    public void unlock() {
        //尝试释放,并且还要唤醒正在阻塞的线程
        sync.release(0);
    }

    @Override //创建一个条件变量
    public Condition newCondition() {
        return sync.newCondition();
    }
}
